package org.base23.video.repository;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.base23.video.domain.entity.AiGuidanceMessageEntity;
import org.base23.video.mapper.AiGuidanceMessageMapper;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;

/**
 * AI指导对话消息 Repository
 */
@Repository
public class AiGuidanceMessageRepository extends ServiceImpl<AiGuidanceMessageMapper, AiGuidanceMessageEntity> {

    /**
     * 保存消息
     */
    public boolean saveMessage(AiGuidanceMessageEntity message) {
        if (message.getTimestamp() == null) {
            message.setTimestamp(LocalDateTime.now());
        }
        if (message.getSequenceNumber() == null) {
            // 自动设置序列号
            Integer maxSequence = baseMapper.selectMaxSequenceByConversationId(message.getConversationId());
            message.setSequenceNumber(maxSequence + 1);
        }
        return save(message);
    }

    /**
     * 根据会话ID查询消息列表（按序列号排序）
     */
    public List<AiGuidanceMessageEntity> findByConversationIdOrderBySequence(String conversationId) {
        return baseMapper.selectByConversationIdOrderBySequence(conversationId);
    }

    /**
     * 根据会话ID分页查询消息
     */
    public IPage<AiGuidanceMessageEntity> findPageByConversationId(String conversationId, int current, int size) {
        Page<AiGuidanceMessageEntity> page = new Page<>(current, size);
        return baseMapper.selectPageByConversationId(page, conversationId);
    }

    /**
     * 获取会话中的最大序列号
     */
    public Integer getMaxSequenceByConversationId(String conversationId) {
        return baseMapper.selectMaxSequenceByConversationId(conversationId);
    }

    /**
     * 统计会话消息数量
     */
    public Integer countByConversationId(String conversationId) {
        return baseMapper.countByConversationId(conversationId);
    }

    /**
     * 查询会话最后一条消息
     */
    public AiGuidanceMessageEntity findLastMessageByConversationId(String conversationId) {
        LambdaQueryWrapper<AiGuidanceMessageEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AiGuidanceMessageEntity::getConversationId, conversationId)
               .orderByDesc(AiGuidanceMessageEntity::getSequenceNumber)
               .last("LIMIT 1");
        return getOne(wrapper);
    }

    /**
     * 删除指定时间之前的消息
     */
    public int deleteByTimestampBefore(LocalDateTime timestamp) {
        return baseMapper.deleteByTimestampBefore(timestamp);
    }

    /**
     * 根据会话ID删除消息
     */
    public int deleteByConversationId(String conversationId) {
        return baseMapper.deleteByConversationId(conversationId);
    }

    /**
     * 批量插入消息
     */
    public boolean insertBatch(List<AiGuidanceMessageEntity> messages) {
        if (messages == null || messages.isEmpty()) {
            return true;
        }
        
        // 为没有序列号的消息设置序列号
        for (int i = 0; i < messages.size(); i++) {
            AiGuidanceMessageEntity message = messages.get(i);
            if (message.getTimestamp() == null) {
                message.setTimestamp(LocalDateTime.now());
            }
            if (message.getSequenceNumber() == null) {
                message.setSequenceNumber(i + 1);
            }
        }
        
        return baseMapper.insertBatch(messages) > 0;
    }

    /**
     * 查询用户在某个时间段内的消息
     */
    public List<AiGuidanceMessageEntity> findMessagesByTimeRange(String conversationId, 
                                                                LocalDateTime startTime, 
                                                                LocalDateTime endTime) {
        LambdaQueryWrapper<AiGuidanceMessageEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AiGuidanceMessageEntity::getConversationId, conversationId)
               .between(AiGuidanceMessageEntity::getTimestamp, startTime, endTime)
               .orderByAsc(AiGuidanceMessageEntity::getSequenceNumber);
        return list(wrapper);
    }

    /**
     * 查询最近的n条消息
     */
    public List<AiGuidanceMessageEntity> findRecentMessages(String conversationId, int limit) {
        LambdaQueryWrapper<AiGuidanceMessageEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AiGuidanceMessageEntity::getConversationId, conversationId)
               .orderByDesc(AiGuidanceMessageEntity::getSequenceNumber)
               .last("LIMIT " + limit);
        return list(wrapper);
    }
} 